package com.guaoran.study.screenshot;

/**
 * @author : gu cheng
 * @description : 截图
 * @date : 2021/8/11 14:15
 */

import com.ruiyun.jvppeteer.core.Puppeteer;
import com.ruiyun.jvppeteer.core.browser.Browser;
import com.ruiyun.jvppeteer.core.browser.BrowserFetcher;
import com.ruiyun.jvppeteer.core.page.ElementHandle;
import com.ruiyun.jvppeteer.core.page.Page;
import com.ruiyun.jvppeteer.options.LaunchOptions;
import com.ruiyun.jvppeteer.options.LaunchOptionsBuilder;
import com.ruiyun.jvppeteer.options.ScreenshotOptions;
import com.ruiyun.jvppeteer.options.WaitForSelectorOptions;
import com.ruiyun.jvppeteer.protocol.network.CookieParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import sun.misc.BASE64Encoder;
import java.io.File;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
@Slf4j
public class ScreenshotExample {

    public static void main(String[] args) throws InterruptedException, IOException, ExecutionException {
        BrowserFetcher.downloadIfNotExist(null);
        ArrayList<String> arrayList = new ArrayList<>();
        String path = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe";
        LaunchOptions options = new LaunchOptionsBuilder().withArgs(arrayList).withHeadless(true).withExecutablePath(path).build();
        arrayList.add("--no-sandbox");
        arrayList.add("--disable-setuid-sandbox");
        Browser browser = null;
        try {
            browser = Puppeteer.launch(options);
            Page page = browser.newPage();

            // 登录
            List<CookieParam> cookieParams = new ArrayList<>();
            CookieParam cookieParam = new CookieParam();
            page.setCookie(createAndGetCookies());


            page.waitFor("10000");
            page.goTo("https://jxg.uat.sunyur.com/purchaser/#/analysis/charts-dinamic/lock_board_006");


            // 根据dom判断是否加载完
            WaitForSelectorOptions waitForSelectorOptions = new WaitForSelectorOptions();
            waitForSelectorOptions.setTimeout(1000*15);
            waitForSelectorOptions.setVisible(Boolean.TRUE);
            ElementHandle elementHandle = page.waitForSelector("testdom", waitForSelectorOptions);

            ScreenshotOptions screenshotOptions = new ScreenshotOptions();
            screenshotOptions.setType("png");
            screenshotOptions.setFullPage(Boolean.TRUE);
            screenshotOptions.setPath("test-1-"+new Random().nextInt(10) +".png");
            //设置截图范围
            //Clip clip = new Clip(1.0,1.56,400,400);
            //screenshotOptions.setClip(clip);

            //设置存放的路径
            page.screenshot(screenshotOptions);
            System.out.println("====================执行结束");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(browser != null){
                browser.close();
            }
        }
    }


    /**
     * 获取 cookie
     * @return
     */
    private static List<CookieParam> createAndGetCookies() {
        List<CookieParam> cookieParams = null;
        int num = 0;
        do {
            cookieParams = loginAndGetCookies();
            num ++;
        } while (num < 3 && CollectionUtils.isEmpty(cookieParams));

        return cookieParams;
    }

    /**
     * 登录获取 cookie
     * @return
     */
    private static List<CookieParam> loginAndGetCookies() {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String jobNumber = base64Encoder.encode("00310".getBytes());
        // 登陆 Url
        String loginUrl = "customPropertiesConfig.getDataSubscribeScreenshotLoginUrl() + jobNumber";
        HttpClient httpClient = new HttpClient();
        // 模拟登陆，按实际服务器端要求选用 Post 或 Get 请求方式
        GetMethod getMethod = new GetMethod(loginUrl);
        try {
            // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
            httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            int statusCode = httpClient.executeMethod(getMethod);
            if(statusCode == 200) {
                // 获得登陆后的 Cookie
                Cookie[] cookies = httpClient.getState().getCookies();
                List<CookieParam> cookieParamList = Arrays.stream(cookies).map(c -> {
                    CookieParam cookieParam = new CookieParam();
                    cookieParam.setName(c.getName());
                    cookieParam.setValue(c.getValue());
                    cookieParam.setPath(c.getPath());
                    cookieParam.setDomain(c.getDomain());
                    cookieParam.setExpires(c.getExpiryDate().getTime()/1000);
                    return cookieParam;
                }).collect(Collectors.toList());
                return cookieParamList;
            }
        } catch (Exception e) {
            log.warn("getCookie Exception:",e);
        }
        return null;
    }


}